package com.hzit.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.hzit.constant.HzitConstants;
import com.hzit.entity.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户鉴权过滤器
 */
@Component
public class HzitAuthFilter extends OncePerRequestFilter {
	@Autowired
	private StringRedisTemplate redisTemplate;
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		//1. 从请求头中取得token值
		String token = request.getHeader("token");
		String token1 = request.getParameter("token");  // 将token放到了请求参数中

		//2. 判断是否有值
		if(!StringUtils.hasText(token)){
			filterChain.doFilter(request,response);
			return;
		}
		//2. 判断是否为null，不为null就组装一个rediskey，从而得到redis的值，就是登录用户
		if(StrUtil.isNotBlank(token)){
			//2.1 根据redis的key获取值
			String key = getKey(token);
			String s = redisTemplate.opsForValue().get(key);
			//2.2 如果不为null，解析得到登录用户
			if(StrUtil.isNotBlank(s)){
				// LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
				// 使用hutool工具进行反序列化
				LoginUser loginUser = JSONUtil.toBean(s, LoginUser.class);
				//2.3 构造认证成功的对象
				Authentication authenticate = new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
				//2.4 向当前的认证对象向后传递（保存在一个线程本地变量ThreadLocal中）
				SecurityContextHolder.getContext().setAuthentication(authenticate);
			}
		}
		// 放行过滤器
		filterChain.doFilter(request,response);
	}

	private String getKey(String token) {
		return HzitConstants.LOGIN_TOKEN_PREFIX + token;
	}
}
